<script setup name="MDTK">
import { ArrowRight } from '@element-plus/icons-vue'
import {
	PeriodicTable,
	NavBar,
	ResultViews,
	ConductivityResultView,
	phase,
	point,
	line,
	meltProperties,
	conductivity,
} from './components'

import { lStorage } from '@/utils/storage'
import { ref, computed } from 'vue'
import {
	elementObj,
	getAvailableElements,
	findMatchedCombination,
} from './utils/config'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'
import {
	binplotPhase, // 二元相图
	ternplotPhase, // 三元相图
	fourPhase, // 四元相图
	lineTempRange, // 温度范围线
	lineCompRange, // 成分范围线
	equilibriumEndpoint, //  点图
} from '@/api/test'
import { calculateConductivity } from '@/api/product/mdtk'

const { t } = useI18n()

// 添加tabs变量
const tabs = ref([
	{
		name: '热物性质计算',
		enName: 'Melt Properties',
		id: '1',
		component: 'meltProperties',
	},
	{
		name: '表面张力计算',
		enName: 'Surface Tension',
		id: '1-1',
		component: 'meltProperties',
	},
])

const activeName = ref('元素')
const currentCalculationType = ref('') // 当前计算类型
const currentCalculationTypeZh = ref('') // 当前计算类型 中文

// 添加计算相关状态变量
const isLoading = ref(false)
const resultData = ref({})
const resultType = ref('image')

// 数据库
const baseData = ref('Mg_based Alloys')
const database = ref([
	{ value: 'Mg_based Alloys', label: 'Mg_based Alloys' },
	{ value: 'Binary Alloys', label: 'Binary Alloys' },
	{ value: 'Fe_based Alloys', label: 'Fe_based Alloys' },
	{ value: 'Al_based Alloys', label: 'Al_based Alloys' },
	{ value: 'Cementite Carbide', label: 'Cementite Carbide' },
	{ value: 'Cu_based Alloys', label: 'Cu_based Alloys' },
	{ value: 'Ni_based Alloys', label: 'Ni_based Alloys' },
])
const sourceData = ref('Mat.Design')

// 可点击的元素数组
const hasDataElements = computed(
	() => elementObj[currentCalculationTypeZh.value]?.可选元素 || []
)
// 当前选中的元素数组
const selectedElements = ref([])
// 计算可点击的元素（基于当前选择状态和配置）
const clickableElements = computed(() => {
	// 分阶段处理可选元素
	return currentCalculationType.value === 'Conductivity'
		? hasDataElements.value
		: getAvailableElements(
				elementObj[currentCalculationTypeZh.value],
				selectedElements.value
			)
})
// 元素组
const elementalGroup = ref('')

// 组件映射
const componentMap = {
	ResultViews, // 结果视图
	ConductivityResultView, // 热导率/电导率结果视图
	phase, // 相图
	point, // 点图
	line, // 线图
	meltProperties, // 粘度/表面张力
	conductivity, // 热导率/电导率
}

const placeholder = ref({
	text: 'mainPage.ui.selectedElementsHint',
	max: 3,
})
const isComponent = ref('')
const isResultComponent = ref('')

// 是否显示提示
const isPrompt = computed(() => {
	return currentCalculationType.value === 'Conductivity'
		? selectedElements.value.length > 1
		: !!elementalGroup.value
})

const locales = computed(() => lStorage.getReactive().value.language || 'zh')

// 菜单选择事件
const handleMenuSelect = (data) => {
	activeName.value = '元素'
	selectedElements.value = []
	elementalGroup.value = ''
	resultData.value = {}
	resultType.value = 'image'
	tabs.value = data.breadcrumb

	if (tabs.value.length === 2) {
		currentCalculationType.value = tabs.value[1].enName
		currentCalculationTypeZh.value = tabs.value[1].name
		selectedElements.value = []
		// 如果是热导率/电导率计算，则需要设置结果组件为ConductivityResultView
		if (tabs.value[1].name === '热导率/电导率计算') {
			isResultComponent.value = 'ConductivityResultView'
			placeholder.value.max = 6
			selectedElements.value = ['Mg']
		}
		// 如果是粘度计算或表面张力计算，则需要设置结果组件为空
		else if (['粘度计算', '表面张力计算'].includes(tabs.value[1].name)) {
			isResultComponent.value = ''
			placeholder.value.max = 3
		}
		// 如果是其他计算，则需要设置结果组件为ResultViews
		else {
			isResultComponent.value = 'ResultViews'
			if (['线计算', '二元相图'].includes(tabs.value[1].name)) {
				placeholder.value.max = 2
			}
			if (['点计算', '三元等温截面'].includes(tabs.value[1].name)) {
				placeholder.value.max = 3
			}
			if (['高元等温截面'].includes(tabs.value[1].name)) {
				placeholder.value.max = 4
			}
		}
		isComponent.value = tabs.value[1].component
	}
}

// 点击元素卡片事件
const onElementClick = (data) => {
	const elementSymbol = data.symbol
	// 热导率/电导率计算最多选择6个元素
	const maxElements =
		currentCalculationType.value === 'Conductivity' ? 7 : placeholder.value.max
	// 如果是热导率/电导率计算，Mg元素不可取消
	if (
		currentCalculationType.value === 'Conductivity' &&
		elementSymbol === 'Mg'
	) {
		return
	}
	// 检查是否已经选择了该元素
	if (selectedElements.value.includes(elementSymbol)) {
		// 如果已选择，则移除该元素及其后面的所有元素
		selectedElements.value = selectedElements.value.filter(
			(e) => e !== elementSymbol
		)
	} else {
		// 如果未选择且未达到最大数量，则添加该元素
		if (selectedElements.value.length < maxElements) {
			selectedElements.value.push(elementSymbol)
		} else {
			// 如果已达到最大数量，替换最后一个元素
			selectedElements.value[maxElements - 1] = elementSymbol
		}
	}

	elementalGroup.value = findMatchedCombination(
		elementObj[currentCalculationTypeZh.value],
		selectedElements.value
	)

	console.log(selectedElements.value, elementalGroup.value)
}

const handleSubmit = async (data) => {
	console.log(data, 'asdasd', currentCalculationTypeZh.value)
	let res = null
	let params = {}
	let api = null
	try {
		isLoading.value = true
		activeName.value = '计算结果'
		switch (currentCalculationTypeZh.value) {
			case '热导率/电导率计算':
				res = await calculateConductivity(data)
				resultData.value = res
				break
			case '线计算':
				params = { ...data }
				delete params.calculationMode
				params.elements = params.elements.join(',').toUpperCase()
				params.comp1 = params.comp1.toUpperCase()
				api =
					data.calculationMode === 'temp_range' ? lineTempRange : lineCompRange
				res = await api(params)
				if (res && res.code === 200 && res.data && res.data.data) {
					// 处理base64格式的图片数据
					const base64Image = res.data.data
					resultData.value = `data:image/png;base64,${base64Image}`
					resultType.value = 'image'
				}
				break
			case '点计算':
				params = { ...data }
				params.elements = params.elements.join(',').toUpperCase()
				params.comp1 = params.comp1.toUpperCase()
				params.comp2 = params?.comp2?.toUpperCase()

				res = await equilibriumEndpoint(params)

				resultType.value = 'table'

				const obj = {
					GM: 'Gibbs energy',
					HM: 'Enthalpy',
					SM: 'Entropy',
				}
				resultData.value = Object.keys(res.data).map((key) => {
					return {
						property: obj[key],
						key: key,
						value: res.data[key],
						unit: key !== 'SM' ? 'J/mol' : 'J/(mol·K)',
					}
				})
				console.log(resultData.value, 'resultData')
				break
			// 相图模块
			default:
				params = { ...data }
				delete params.calculationMode
				params.elements = params.elements.join(',').toUpperCase()
				switch (data.elements.length) {
					case 2:
						api = binplotPhase
						break
					case 3:
						api = ternplotPhase
						break
					case 4:
						api = fourPhase
					default:
						break
				}
				try {
					res = await api(params)
					if (res?.code === 200 && res.data?.data) {
						resultData.value = `data:image/png;base64,${res.data.data}`
						resultType.value = 'image'
					} else {
						console.error('API returned invalid data:', res)
						throw new Error('Failed to generate phase diagram')
					}
				} catch (error) {
					console.error('API call failed:', error)
					throw error // 或返回兜底结果
				}
				break
		}
		isLoading.value = false
	} catch (error) {
		isLoading.value = false
	}
}

onMounted(() => {
	handleMenuSelect({
		key: '1-1',
		keyPath: ['1', '1-1'],
		breadcrumb: [
			{
				name: '热物性质计算工具',
				enName: 'Melt Properties Tools',
			},
			{
				name: '表面张力计算',
				enName: 'Surface Tension',
				component: 'meltProperties',
			},
		],
	})
})
</script>

<template>
	<div class="MDTK">
		<div class="nav-bar">
			<NavBar @menuSelect="handleMenuSelect" />
		</div>

		<div class="content">
			<div class="content-tab">
				<el-breadcrumb :separator-icon="ArrowRight">
					<el-breadcrumb-item
						v-for="(tab, index) in [
							{
								name: t('mainPage.title'),
								enName: t('mainPage.enTitle'),
								id: 'platform',
							},
							...(tabs || []),
						]"
						:key="tab.id || `tab-${index}`"
					>
						{{ locales === 'zh' ? tab.name : tab.enName }}
					</el-breadcrumb-item>
				</el-breadcrumb>
			</div>
			<div class="content-main">
				<div class="content-main-top">
					<div class="content-main-top-select-group">
						<div class="content-main-top-select">
							<label>{{ t('mainPage.ui.database') }}</label>
							<el-select
								v-model="baseData"
								:placeholder="t('mainPage.ui.selectDatabase')"
							>
								<el-option
									v-for="(item, index) in database"
									:key="index"
									:label="item.label"
									:value="item.value"
									:disabled="true"
								/>
							</el-select>
						</div>

						<div class="content-main-top-select">
							<label>{{ t('mainPage.ui.source') }}</label>
							<el-select
								v-model="sourceData"
								:placeholder="t('mainPage.ui.selectSource')"
							>
								<el-option label="Mat.Design" value="Mat.Design" />
							</el-select>
						</div>
					</div>
				</div>
				<div class="content-main-bottom">
					<div class="content-main-bottom-left">
						<el-tabs v-model="activeName" class="content-main-bottom-left-tabs">
							<el-tab-pane label="元素" name="元素">
								<PeriodicTable
									:hasDataElements="hasDataElements"
									:clickableElements="clickableElements"
									:selectedElements="selectedElements"
									@elementClick="onElementClick"
								/>
							</el-tab-pane>
							<el-tab-pane
								label="计算结果"
								name="计算结果"
								v-if="
									!['表面张力计算', '粘度计算'].includes(
										currentCalculationTypeZh
									)
								"
							>
								<component
									:is="componentMap[isResultComponent]"
									:isLoading="isLoading"
									:resultData="resultData"
									:type="currentCalculationTypeZh"
									:resultType="resultType"
									:title="currentCalculationTypeZh"
								/>
							</el-tab-pane>
						</el-tabs>
					</div>
					<div class="content-main-bottom-right">
						<div class="content-main-bottom-right-title">
							<span class="title-text">计算工具</span>
						</div>
						<div class="content-main-bottom-right-content">
							<el-form label-width="100px">
								<el-form-item label="选中元素">
									<el-input
										:value="selectedElements.join(' + ')"
										:placeholder="
											t(placeholder.text, {
												count: selectedElements.length,
												max: placeholder.max,
											})
										"
										:rows="currentCalculationType === 'Conductivity' ? 2 : 1"
										type="textarea"
										resize="none"
										readonly
									/>
								</el-form-item>

								<el-form-item label="组元素" v-if="elementalGroup">
									<el-input
										:value="elementalGroup.split('-').join('_').split('.')[0]"
										resize="none"
										readonly
									/>
								</el-form-item>
							</el-form>

							<!-- 组件展示区域 -->
							<div class="component-container">
								<!-- 相图计算组件需要元素选择 -->
								<div v-if="isPrompt">
									<component
										:is="componentMap[isComponent]"
										:elementalGroup="elementalGroup"
										:selectedElements="selectedElements"
										:isLoading="isLoading"
										:type="currentCalculationTypeZh"
										@on-submit="handleSubmit"
									/>
								</div>
								<div v-else class="no-calculation-hint">
									{{
										currentCalculationType === 'Conductivity'
											? t('mainPage.messages.selectElementsHint', { max: 6 })
											: ['点计算'].includes(currentCalculationTypeZh)
												? '请选择2~3种元素开始匹配计算组合'
												: `请选择${placeholder.max}种元素开始匹配计算组合`
									}}
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<style scoped lang="scss">
@import url('@/styles/content/index.scss');

.MDTK {
	min-height: calc(100vh - 72px);
	height: 100%;
	width: 100%;
	display: flex;
	box-sizing: border-box;
	.nav-bar {
		width: 240px;
	}
	.content {
		flex: 1;
		&-tab {
			height: 52px;
			border-bottom: 1px solid var(--theme-content-border);
			display: flex;
			align-items: center;
			padding: 0 20px;
			box-sizing: border-box;
			background-color: var(--theme-card-bg);

			:deep(.el-breadcrumb__item) {
				.el-breadcrumb__inner,
				.el-breadcrumb__separator {
					color: var(--theme-text-primary);
				}
				&:last-child {
					.el-breadcrumb__inner {
						font-weight: bold;
					}
				}
			}
		}
		&-main {
			height: calc(100% - 52px);
			display: flex;
			flex-direction: column;
			padding: 20px;
			box-sizing: border-box;
			display: flex;
			flex-direction: column;
			gap: 20px;
			&-top {
				height: 72px;
				background-color: var(--theme-card-bg);
				box-sizing: border-box;
				border: 1px solid var(--theme-content-border);
				box-shadow: 0 0 10px 0 var(--theme-content-border);
				box-sizing: border-box;
				padding: 0 20px;
				justify-content: flex-start;
				display: flex;
				&-select-group {
					display: flex;
					align-items: center;
					gap: 20px;
				}
				&-select {
					display: flex;
					align-items: center;
					gap: 10px;
					background-color: var(--theme-accent);
					label {
						font-size: 12px;
						color: var(--ptable-text-highlight);
						font-weight: bold;
						padding: 0 8px 0 24px;
					}
					:deep(.el-select) {
						width: 240px;

						.el-select__wrapper {
							border-radius: 16px 0 0 16px !important;
							padding: 0 20px;
							border: none !important;
							background-color: #fff !important;
							color: var(--ptable-text-highlight);
							font-weight: bold;
						}
						.el-select__selected-item {
							color: var(--input-placeholder);
						}
					}
				}
			}

			&-bottom {
				flex: 1;
				display: flex;

				box-sizing: border-box;
				&-left {
					flex: 3;
					background-color: var(--theme-card-bg);
					padding: 20px;
					box-sizing: border-box;

					&-tabs {
						height: 100%;
						:deep(.el-tabs__content) {
							padding: 10px 0;
							box-sizing: border-box;
							height: calc(100% - 40px);
							display: flex;
							align-items: center;
							justify-content: center;
						}
						:deep(.el-tabs__item) {
							color: var(--theme-text-primary) !important;
						}
						:deep(.is-active) {
							color: var(--ptable-bg-highlight) !important;
						}
						:deep(.el-tabs__nav-wrap) {
							&::after {
								background-color: var(--theme-content-border);
							}
						}
					}
				}
				&-right {
					width: 360px;
					box-sizing: border-box;
					padding: 20px;
					padding-top: 0;
					background-color: var(--theme-card-bg);
					&-title {
						display: flex;
						align-items: center;
						justify-content: space-between;
						border-bottom: 2px solid var(--theme-content-border);
						height: 60px;
						margin-bottom: 10px;

						.title-text {
							font-size: 18px;
							font-weight: bold;
						}
					}
					&-content {
						.component-container {
							// 组件容器样式已经在各个组件内部定义
						}

						.no-calculation-hint {
							padding: 20px;
							text-align: center;
							color: var(--theme-text-secondary);
							background: var(--theme-bg-secondary);
							border-radius: 8px;
							border: 1px dashed var(--theme-content-border);
							margin-top: 16px;
						}

						.no-result-hint {
							padding: 20px;
							text-align: center;
							color: var(--theme-text-secondary);
							background: var(--theme-bg-secondary);
							border-radius: 8px;
							border: 1px dashed var(--theme-content-border);
							margin-top: 16px;
						}

						.no-result-content {
							display: flex;
							flex-direction: column;
							align-items: center;
							gap: 10px;
						}

						.no-result-icon {
							color: var(--theme-text-secondary);
						}

						.no-result-text {
							font-size: 16px;
							font-weight: bold;
							color: var(--theme-text-primary);
						}

						.no-result-description {
							font-size: 14px;
							color: var(--theme-text-secondary);
						}

						:deep(.el-form-item) {
							margin-bottom: 15px;

							.el-form-item__label {
								font-weight: 600;
								color: var(--theme-content-title);
							}
							.el-form-item__error {
								display: none;
							}
						}
					}
				}
			}
		}
	}
}
</style>

<style>
@import url('@/styles/element-plus/form.scss');
</style>
